import glob from 'glob'
import { join } from 'path'
import config from '../../server/config'
const mongoose = require('mongoose')
mongoose.Promise = global.Promise
const db = config.db

glob.sync(join(__dirname, '../database/schema', '**/*.js')).forEach(require)

export const database = app => {
	let maxConnectTimes = 0

	return new Promise((resolve, reject) => {
		if (process.env.NODE_ENV !== 'production') {
			mongoose.set('debug', true)
		}

		mongoose.connect(db)

		mongoose.connection.on('disconnected', () => {
			maxConnectTimes++
			if (maxConnectTimes < 5) {
				mongoose.connect(db)	
			} else {
				throw new Error('数据库挂了')
			}
			
		})

		mongoose.connection.on('err', (err) => {
			maxConnectTimes++
			if (maxConnectTimes < 5) {
				mongoose.connect(db)	
			} else {
				throw new Error('数据库挂了')
			}
		})

		mongoose.connection.once('open', () => {
			resolve()
			console.log('mongodb connected successfully!!!')
		})

		// const Question = mongoose.model('Question')
		// const question = new Question({
		// 	courseid: '1001',
		// 	topic: '主题3',
		// 	email: 'aaa@',
		// 	content: '<pre-code></pre-code>'
		// })

		// question.save().then((res) => {
		// 	console.log(res)
		// })
	})

}









